using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {
    internal class InspectorField_MaskLink : InspectorField<AGAFieldModel_MaskLink> {
        ObjectField maskField;

        protected override void BuildUI() {
            maskField = new ObjectField(labelText);
            maskField.objectType = typeof(AvatarMask);
            if (ageContext.resourceManager.GetResource(source.maskKey, out var entry)) {
                maskField.value = entry.resource;
            }
            maskField.RegisterValueChangedCallback(OnMaskChange);
        }

        protected override void DrawUI() {
            Add(maskField);
        }

        private void OnMaskChange(ChangeEvent<UnityEngine.Object> evt) {
            if (evt.previousValue != null) {
                ageContext.resourceManager.TryRemoveResource(source.maskKey);
                source.maskKey = default;
            }
            if (evt.newValue != null) {
                var uuid = ageContext.resourceManager.AddResource(evt.newValue, AGAResourceType.Mask);
                source.maskKey = uuid;
            }

            inspectorChangeCallback?.Invoke();
        }
    }
}
